package com.bayihouse.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bayihouse.annotation.AuthCheck;
import com.bayihouse.common.BaseResponse;
import com.bayihouse.common.DeleteRequest;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.common.ResultUtils;
import com.bayihouse.constant.AdministerConstant;
import com.bayihouse.constant.AdministerConstant;
import com.bayihouse.exception.BusinessException;
import com.bayihouse.exception.ThrowUtils;
import com.bayihouse.model.entity.Occupant;
import com.bayihouse.model.entity.Rentinfo;
import com.bayihouse.model.request.occupant.OccupantUpdateRequest;
import com.bayihouse.model.request.rentinfo.RentinfoAddRequest;
import com.bayihouse.model.request.rentinfo.RentinfoQueryRequest;
import com.bayihouse.model.request.rentinfo.RentinfoUpdateRequest;
import com.bayihouse.model.vo.RentinfoVO;
import com.bayihouse.service.*;
import com.bayihouse.utils.MinioUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/rentinfo")
@Slf4j
public class RentinfoController {


    @Resource
    private RentinfoService rentinfoService;

    @Resource
    private FileInfoService fileInfoService;

    @Resource
    private MinioUtils minioService;


    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param rentinfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Long> addRentinfo(@RequestBody RentinfoAddRequest rentinfoAddRequest, HttpServletRequest request) {
        if (rentinfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        System.out.println(rentinfoAddRequest);
        Rentinfo rentinfo = new Rentinfo();
        Gson gson = new Gson();
        BeanUtils.copyProperties(rentinfoAddRequest, rentinfo);
        if (rentinfoAddRequest.getDisplayid() != null) {
            rentinfo.setDisplayid(gson.toJson(rentinfoAddRequest.getDisplayid()));
        }
        boolean result = rentinfoService.save(rentinfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(rentinfo.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteRentinfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = rentinfoService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }


    @PostMapping("/update")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> updateRentInfo(@RequestBody RentinfoUpdateRequest rentinfoUpdateRequest,
                                                HttpServletRequest request) {
        System.out.println("请求" + rentinfoUpdateRequest);
        if (rentinfoUpdateRequest == null || rentinfoUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Rentinfo rentinfo = new Rentinfo();
        Gson gson = new Gson();
        if (rentinfoUpdateRequest.getOccupantIds() == null) {
            rentinfo.setStatus(0);
        } else if (rentinfoUpdateRequest.getOccupantIds().size() == 0) {
            rentinfo.setStatus(0);
        } else {
            rentinfo.setStatus(1);
        }
        rentinfo.setOccupantIds(gson.toJson(rentinfoUpdateRequest.getOccupantIds()));
        BeanUtils.copyProperties(rentinfoUpdateRequest, rentinfo);
        boolean result = rentinfoService.updateById(rentinfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<RentinfoVO> getRentinfoById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Rentinfo rentinfo = rentinfoService.getById(id);
        ThrowUtils.throwIf(rentinfo == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(RentinfoVO.objToVo(rentinfo));
    }

    public BaseResponse<Rentinfo> getRentinfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Rentinfo rentinfo = rentinfoService.getById(id);
        ThrowUtils.throwIf(rentinfo == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(rentinfo);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<RentinfoVO> getRentinfoVOById(long id, HttpServletRequest request) {
        BaseResponse<Rentinfo> response = getRentinfoById(id);
        Rentinfo rentinfo = response.getData();
        return ResultUtils.success(rentinfoService.getRentinfoVO(rentinfo));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param rentinfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Rentinfo>> listRentinfoByPage(@RequestBody RentinfoQueryRequest rentinfoQueryRequest,
                                                           HttpServletRequest request) {
        long current = rentinfoQueryRequest.getCurrent();
        long size = rentinfoQueryRequest.getPageSize();
        Page<Rentinfo> rentinfoPage = rentinfoService.page(new Page<>(current, size),
                rentinfoService.getQueryWrapper(rentinfoQueryRequest));
        return ResultUtils.success(rentinfoPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param rentinfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<RentinfoVO>> listRentinfoVOByPage(@RequestBody RentinfoQueryRequest rentinfoQueryRequest,
                                                               HttpServletRequest request) {
        if (rentinfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = rentinfoQueryRequest.getCurrent();
        long size = rentinfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Rentinfo> rentinfoPage = rentinfoService.page(new Page<>(current, size),
                rentinfoService.getQueryWrapper(rentinfoQueryRequest));
        System.out.println(rentinfoPage.getRecords());
        Page<RentinfoVO> rentinfoVOPage = new Page<>(current, size, rentinfoPage.getTotal());
        List<RentinfoVO> rentinfoVOList = getRentinfoVOList(rentinfoPage.getRecords());
        rentinfoVOPage.setRecords(rentinfoVOList);
        System.out.println(rentinfoVOPage.getRecords());
        return ResultUtils.success(rentinfoVOPage);
    }

    public List<RentinfoVO> getRentinfoVOList(List<Rentinfo> rentinfoList) {
        if (CollectionUtils.isEmpty(rentinfoList)) {
            return new ArrayList<>();
        }
        Gson gson = new Gson();
        List<RentinfoVO> rentinfoVOList = rentinfoList.stream().map(rentinfo -> {
            RentinfoVO rentinfoVO = RentinfoVO.objToVo(rentinfo);
            List<Long> displayIds = gson.fromJson(rentinfo.getDisplayid(), new TypeToken<List<String>>() {
            }.getType());
            if (!CollectionUtils.isEmpty(displayIds)) {
                List<String> displayUrls = fileInfoService.getDisplayUrls(displayIds);
                rentinfoVO.setDisplayUrls(displayUrls);
            }
            return rentinfoVO;
        }).collect(Collectors.toList());
        return rentinfoVOList;
    }


}


